package org.atovio.coolexam.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.atovio.coolexam.common.Result;
import org.atovio.coolexam.common.Role;
import org.atovio.coolexam.entity.User;
import org.atovio.coolexam.exception.RequestException;
import org.atovio.coolexam.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController("AdminUserController")
@RequestMapping("/users")
@Slf4j
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public Result addUser(@RequestBody User user) {
        return Result.success(userService.addUser(user));
    }

    @GetMapping("/role")
    public Result queryUserByRole(@RequestParam Role role) {
        return Result.success(userService.getByRole(role));
    }

    @GetMapping("/role/username")
    public Result queryUserByRoleAndUserName(@RequestParam Role role, @RequestParam String userName) {
        return Result.success(userService.getByRoleLikeUserName(role, userName));
    }

    @PutMapping
    public Result modifyUser(@RequestBody User user) {
        return Result.success(userService.modifyUser(user));
    }

    @DeleteMapping("/{userId}")
    public Result deleteUser(@PathVariable Integer userId) {
        userService.deleteByUserId(userId);
        return Result.success();
    }

    @PutMapping("/username")
    public Result modifyUsername(@RequestBody User user) {
        return Result.success(userService.modifyUserName(user));
    }

    @PutMapping("/password")
    public Result modifyPassword(@RequestBody JsonNode jsonNode) throws JsonProcessingException {
        // 解析数据
        JsonNode userJson = jsonNode.get("user");
        String oldPassword = jsonNode.get("oldPassword").asText();
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.treeToValue(userJson, User.class);
        // 验证和改密
        if (Objects.isNull(user)) {
            throw new RequestException("User数据异常!!!");
        }
        return Result.success(userService.modifyPassword(user, oldPassword));
    }

    @PutMapping("/imagePath")
    public Result modifyImagePath(@RequestBody User user) {
        return Result.success(userService.modifyImagePath(user));
    }

}
